<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区 -->
    <el-card>
      <!-- 警告栏 -->
      <el-alert show-icon title="注意 : 只允许为第三级分类设置相关参数! " type="warning">
      </el-alert>
      <!-- 选择商品分类区域 -->
      <el-row :gutter="10" class="cat_opt">
        <span>选择商品分类 : </span>
        <el-cascader v-model="selectCateKeys" :options="cateList" :props="catePropss" @change="handleChange">
        </el-cascader>

      </el-row>
      <!-- tabs切换 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="用户管理" name="many">
          <el-button type="primary" :disabled="isBtnDisabled" @click="dialogVisibleAdd = true">添加参数</el-button>
          <!-- 动态参数表格 -->
          <el-table :data="manyTabData" style="width: 100%" border stripe>
            <el-table-column type="expand" align="center" prop="prop" label="展开" width="70">
              <template slot-scope="{row}">
                <!-- tag标签 -->
                <el-tag :key="index" v-for="(tag,index) in row.attr_vals" closable :disable-transitions="false"
                  @close="handleClose(row,tag)">
                  {{tag}}
                </el-tag>
                <el-input class="input-new-tag" v-if="row.inputVisible" v-model="row.inputValue" ref="saveTagInput"
                  size="small" @keyup.enter.native="$event.target.blur()" @blur="handleInputConfirm(row)">
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(row)">添加</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="序号" width="70">
            </el-table-column>
            <el-table-column prop="attr_name" label="参数名称" width="width">
            </el-table-column>
            <el-table-column label="操作" width="width">
              <template slot-scope="{row}">
                <el-button type="primary" style="margin-right:14px" icon="el-icon-edit" @click="showDialogEdit(row)"
                  size="mini">编辑</el-button>
                <el-popconfirm title="这是一段内容确定删除吗？" @confirm="delPrams(row)">
                  <el-button type="danger" slot="reference" icon="el-icon-delete" size="mini">
                    删除
                  </el-button>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="配置管理" name="only">
          <el-button type="primary" :disabled="isBtnDisabled" @click="dialogVisibleAdd = true">添加属性</el-button>
          <!-- 静态属性表格 -->
          <el-table :data="onlyTabData" style="width: 100%" border stripe>
            <el-table-column type="expand" align="center" prop="prop" label="展开" width="70">
              <template slot-scope="{row}">
                <!-- tag标签 -->
                <el-tag :key="index" v-for="(tag,index) in row.attr_vals" closable :disable-transitions="false"
                  @close="handleClose(row,tag)">
                  {{tag}}
                </el-tag>
                <el-input class="input-new-tag" v-if="row.inputVisible" v-model="row.inputValue" ref="saveTagInput"
                  size="small" @keyup.enter.native="$event.target.blur()" @blur="handleInputConfirm(row)">
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(row)">添加</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="序号" width="70">
            </el-table-column>
            <el-table-column prop="attr_name" label="属性名称" width="width">
            </el-table-column>
            <el-table-column label="操作" width="width">
              <template slot-scope="{row}">
                <el-button type="primary" style="margin-right:14px" icon="el-icon-edit" @click="showDialogEdit(row)"
                  size="mini">编辑</el-button>
                <el-popconfirm title="这是一段内容确定删除吗？" @confirm="delPrams(row)">
                  <el-button type="danger" slot="reference" icon="el-icon-delete" size="mini">
                    删除
                  </el-button>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加属性的对话框 -->
    <el-dialog :title='`添加${titleText}`' :visible.sync="dialogVisibleAdd" width="40%" @close="addDialogClosed">
      <el-form :model="addForm" :rules="addRules" ref="addRuleForm" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleAdd = false">取 消</el-button>
        <el-button type="primary" @click="submitFormAdd">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改参数的对话框 -->
    <el-dialog :title='`修改${titleText}`' :visible.sync="dialogVisibleEdit" width="40%" @close="editDialogClosed">
      <el-form :model="editForm" :rules="addRules" ref="editRuleForm" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogVisibleEdit = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    name: "Params",
    data() {
      return {
        //商品分类列表
        cateList: [],
        // 级联选择框的配置对象
        catePropss: {
          expandTrigger: 'hover',
          value: 'cat_id',
          label: 'cat_name',
          children: "children"
        },
        //级联选择框双向绑定的数组
        selectCateKeys: [],
        //tabs切换的数据
        activeName: "many",
        manyTabData: [],
        onlyTabData: [],
        //添加的对话框显示与隐藏
        dialogVisibleAdd: false,
        //添加参数的数据
        addForm: {},
        //添加参数的表单规则
        addRules: {
          attr_name: [{
            required: true,
            message: '请输入参数名称~',
            trigger: 'blur'
          }, ]
        },
        //修改属性的框子的显示与隐藏 
        dialogVisibleEdit: false,
        //修改参数的数据
        editForm: {},
      }
    },
    methods: {
      //获取商品分类列表数据
      async getCateList() {
        let result = await this.$requests.get("categories")
        if (result.meta.status == 200) {
          this.cateList = result.data
        } else {
          return
        }
      },
      //获取参数列表数据
      async getParamsData() {
        if (this.selectCateKeys.length !== 3) {
          this.selectCateKeys = []
          return
        }
        let result = await this.$requests.get(`categories/${this.cateId}/attributes`, {
          params: {
            sel: this.activeName
          }
        })
        // 把每一项里面的attr_val分隔成数组
        result.data.forEach((item) => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : []
          //控制文本框的显示与隐藏
          this.$set(item, "inputVisible", false)
          this.$set(item, "inputValue", "")
        })
        //判断是哪个面板的数据
        if (this.activeName == "many") {
          this.manyTabData = result.data
        } else {
          this.onlyTabData = result.data
        }

      },
      //级联选择框变化触发的回调
      handleChange() {
        this.getParamsData()
      },
      //切换tabs的回调
      handleClick() {
        this.getParamsData()
      },
      //初始化添加属性的表单数据
      addDialogClosed() {
        this.$refs.addRuleForm.resetFields();
      },
      //添加属性表单提交按钮的回调
      submitFormAdd() {
        this.$refs.addRuleForm.validate(async (valid) => {
          if (valid) {
            let result = await this.$requests.post(`categories/${this.cateId}/attributes`, {
              attr_name: this.addForm.attr_name,
              attr_sel: this.activeName
            })
            if (result.meta.status == 201) {
              this.getParamsData()
              this.dialogVisibleAdd = false
              this.$message.success("添加属性成功")
            } else {
              return this.$message.error("网络不佳,请稍后再试")
            }
          } else {
            this.$message.error("再次检查输入哦")
            return false;
          }
        })
      },
      //修改按钮的回调
      async showDialogEdit(row) {
        let result = await this.$requests.get(`categories/${this.cateId}/attributes/${row.attr_id}`, {
          params: {
            attr_sel: this.activeName
          }
        })
        if (result.meta.status == 200) {
          this.editForm = result.data
        } else {
          this.$message.error("请求失败")
        }
        this.dialogVisibleEdit = true
      },
      //初始化修改属性的表单数据
      editDialogClosed() {
        this.$refs.editRuleForm.resetFields();
      },
      //修改参数弹出框按钮确定的回调
      editParams() {
        this.$refs.editRuleForm.validate(async (valid) => {
          if (valid) {
            let result = await this.$requests.put(
              `categories/${this.cateId}/attributes/${this.editForm.attr_id}`, {
                attr_name: this.editForm.attr_name,
                attr_sel: this.activeName
              })
            if (result.meta.status == 200) {
              this.getParamsData()
              this.$message.success("修改数据成功~")
            } else {
              this.$message.error("网络不佳,请稍后再试~")
            }
          } else {
            this.$message.error("再次检查输入哦")
            return false;
          }
        })
        this.dialogVisibleEdit = false
      },
      //删除按钮的回调
      async delPrams(row) {
        let result = await this.$requests.delete(`categories/${this.cateId}/attributes/${row.attr_id}`)
        if (result.meta.status == 200) {
          this.$message.success("删除成功")
          this.getParamsData()
        } else {
          this.$message.error("网络不佳,请稍后再试")
          return
        }
      },
      handleClose(row, tag) {
        row.attr_vals.splice(row.attr_vals.indexOf(tag), 1);
        this.saveAttrVals(row)

      },
      //点击按钮展示文本框
      showInput(row) {
        row.inputVisible = true;
        this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
      },
      // 对attr_vals的操作  保存到数据库
      async saveAttrVals(row) {
        let result = await this.$requests.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(" ")
        })
        if (result.meta.status == 200) {
          return this.$message.success("操作成功")
        } else {
          return this.$message.error("操作失败")
        }
      },
      //文本框失焦和enter的事件
      async handleInputConfirm(row) {
        let inputValue = row.inputValue.trim();
        if (inputValue) {
          row.attr_vals.push(inputValue);
        }
        row.inputVisible = false;
        row.inputValue = '';

        this.saveAttrVals(row)

      }
    },
    mounted() {
      this.getCateList()
    },
    computed: {
      //按钮是否被禁用
      isBtnDisabled() {
        return this.selectCateKeys.length !== 3
      },
      //选中的三级id
      cateId() {
        return this.selectCateKeys.length === 3 ? this.selectCateKeys[2] : null
      },
      //对话框标题文本
      titleText() {
        if (this.activeName == "only") {
          return "静态属性"
        } else {
          return "动态参数"
        }
      },
    }
  }

</script>

<style lang="less" scoped>
  .cat_opt {
    margin: 15px 0px;
  }

  .el-tag {
    margin: 5px 10px;
  }

  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }

  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }

</style>
